package com.kylin.common.core.mybatis.handlers;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.kylin.common.core.security.SecurityService;
import com.kylin.common.core.util.SpringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;

/**
 * 自定义填充
 *
 * @author wuhao
 * @version 1.0 - 2021-03-19
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("createBy", getUserId(), metaObject);
        this.setFieldValByName("updateBy", getUserId(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", getUserId(), metaObject);
    }
    
    /** 获取用户ID */
    private Serializable getUserId() {
        SecurityService securityService = SpringUtils.getBean(SecurityService.class);
        if(securityService == null) {
            return null;
        } else {
            return securityService.getUserId();
        }
    }
}
